<?php

class Website {
	var $website; //网站配制
	var $action; //php 运行根目录
	public function __construct(&$website) {
		$website['class']['db'] = new Database($website);
		$website['class']['tpl'] = new Template($website);
		$website['class']['err'] = new WebError($website);
		$website['class']['files'] = new Files($website);
		$website['class']['log'] = new Log($website);
		$website['class']['unity'] = new Unity($website);
		$this->website = $website;
	}

	//网站初始化运行
	public function start() {
		if (strpos($this->website['url']['wap'], $_SERVER['HTTP_HOST'])) {
			$this->action = $this->website['path']['mobile'];
		} else {
			$this->action = $this->website['path']['action'];
		}
		// echo $this->action;
		$route = $this->route();
		$addr = $this->action . '/' . $route;

		if (is_file($addr)) {
			try {
				$website = $this->website;
				require_once $addr;
			} catch (EngineException $e) {
				$this->website['class']['err']->manage(array(
					'type' => 'top',
					'msg' => $route . '：' . $e->getMessage(),
				));
				echo json_encode(
					array(
						'status' => 'error',
						'msg' => $e->getMessage(),
					)
				);
				exit();
			}
		} else {
			echo json_encode(array(
				'status'=>'error',
				'msg'=>'错误的地址，请核对后执行！'
			));
		}
	}

	//地址路由分析--返回执行文件地址
	private function route() {
		$act = $_GET['act'] ?? $_POST['act'] ?? false;

		// 支付宝小程序
		if(!$act){
			$params = file_get_contents("php://input");
			if($params){
				$json = $this->params();
				$act = $json['act'];
			}
		}

		$acts = str_replace('-', '/', $act);
		// echo $this->action.'/'.$acts.'.php';
		if (!$act) {
			$addr = 'index.php';
		} elseif (is_file($this->action . '/' . $acts . '.php')) {
			$addr = $acts . '.php';
		} elseif (is_file($this->action . '/' . $acts . '/index.php')) {
			$addr = $acts . '/index.php';
		} else {
			$addr = '/error.php';
		}

		return $addr;
	}

	// 返回数据-zfb
	public function params(){
		$str = file_get_contents('php://input');
		$arr = json_decode($str,1);
		return $arr;
	}

	// 路由端直接输出
	public function json_encode($json, $options = JSON_UNESCAPED_UNICODE, $depth = 512) {
		if ($this->website['database']['db']['sql']) {
			$json['sql'] = $this->website['class']['db']->sql;
		}
		$return = json_encode($json, $options, $depth);

		echo $return;
		exit();
	}

	// 路由端直接加密输出
	public function json_encode_encrypt($json, $options = JSON_UNESCAPED_UNICODE, $depth = 512) {
		if ($this->website['database']['db']['sql']) {
			$json['sql'] = $this->website['class']['db']->sql;
		}
		$return = json_encode($json, $options, $depth);

		echo $return;
		exit();
	}

}
